package com.moore.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.List;

public class SupportUtils {
    public static String insertText(String user, String text) {
        String sql = "insert into chat (user,text) values (?,?)";
        int num;
        try {
            num = JDBCUtils.executeUpdate(sql, user, text);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (num > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    public static String getText() {
        String sql = "select * from chat";
        List<String> list;
        try {
            list = JDBCUtils.executeSelect(sql,"user","text");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 创建一个JSONArray用于存储多个JSONObject
        JSONArray jsonArray = new JSONArray();
        int i = 0;
        while(true) {
            // 检查是否超出范围
            if (2 * i + 1 >= list.size()) {
                break; // 如果超出范围，跳出循环
            }
            // 创建一个新的JSONObject用于存储每条消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("role", list.get(2 * i));
            jsonObject.put("message", list.get(2 * i + 1));
            // 将这个JSONObject添加到JSONArray中
            jsonArray.add(jsonObject);
            i++;
        }
        // 将JSONArray转换为字符串并返回
        return jsonArray.toString();
    }

    public static String clearText() {
        String sql = "delete from chat";
        int num;
        try {
            num = JDBCUtils.executeUpdate(sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (num > 0) {
            return "success";
        } else {
            return "fail";
        }
    }
}
